package com.hanserwei.community.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hanserwei.community.entity.po.ComplaintType;
import com.hanserwei.community.entity.request.complaint.ComplaintTypeSaveRequest;
import com.hanserwei.community.enums.ResponseCodeEnum;
import com.hanserwei.community.mapper.ComplaintTypeMapper;
import com.hanserwei.community.service.ComplaintTypeService;
import com.hanserwei.community.uitils.ThrowUtils;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
@RequiredArgsConstructor
public class ComplaintTypeServiceImpl extends ServiceImpl<ComplaintTypeMapper, ComplaintType> implements ComplaintTypeService {

    @Override
    public boolean createType(ComplaintTypeSaveRequest request) {
        ThrowUtils.throwIf(request == null, ResponseCodeEnum.INVALID_PARAMETER, "参数错误！");
        ThrowUtils.throwIf(!StringUtils.hasText(request.getName()), ResponseCodeEnum.INVALID_PARAMETER, "类型名称不能为空！");
        Long duplicate = lambdaQuery().eq(ComplaintType::getName, request.getName()).count();
        ThrowUtils.throwIf(duplicate != null && duplicate > 0, ResponseCodeEnum.INVALID_PARAMETER, "类型名称已存在！");
        ComplaintType type = new ComplaintType();
        BeanUtils.copyProperties(request, type);
        if (type.getStatus() == null) {
            type.setStatus(1);
        }
        boolean result = save(type);
        ThrowUtils.throwIf(!result, ResponseCodeEnum.SYSTEM_ERROR, "新增失败！");
        return true;
    }

    @Override
    public boolean updateType(Integer id, ComplaintTypeSaveRequest request) {
        ThrowUtils.throwIf(id == null || id <= 0, ResponseCodeEnum.INVALID_PARAMETER, "类型ID参数错误！");
        ThrowUtils.throwIf(request == null, ResponseCodeEnum.INVALID_PARAMETER, "参数错误！");
        ComplaintType type = getById(id);
        ThrowUtils.throwIf(type == null, ResponseCodeEnum.RESOURCE_NOT_FOUND, "类型不存在！");
        if (StringUtils.hasText(request.getName()) && !request.getName().equals(type.getName())) {
            Long duplicate = lambdaQuery()
                    .eq(ComplaintType::getName, request.getName())
                    .ne(ComplaintType::getId, id)
                    .count();
            ThrowUtils.throwIf(duplicate != null && duplicate > 0, ResponseCodeEnum.INVALID_PARAMETER, "类型名称已存在！");
        }
        BeanUtils.copyProperties(request, type);
        boolean result = updateById(type);
        ThrowUtils.throwIf(!result, ResponseCodeEnum.SYSTEM_ERROR, "更新失败！");
        return true;
    }

    @Override
    public List<ComplaintType> listActive() {
        return lambdaQuery().eq(ComplaintType::getStatus, 1).list();
    }
}
